package com.payment.ktb.activity.main4;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.adapter.CityAdapter;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.db.DBHelp;
import com.payment.ktb.model.City;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.CharacterParser;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.PinyinComparator;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;
import com.payment.ktb.view.BladeView;
import com.payment.ktb.view.PinnedHeaderListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/7/28.
 */
public class CityActivity extends BaseActivity implements AdapterView.OnItemClickListener{

    List<City> listData = new ArrayList<City>();
    CityAdapter mCityAdatpter;
    String sqliePath = null;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();


    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @BindView(R.id.phlv_city)
    PinnedHeaderListView phlv_city;
    @BindView(R.id.bv_city)
    BladeView bv_city;
    @BindView(R.id.tv_city_localname)
    TextView tv_city_localname;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city);
        initTitle("选择支行所在城市");
        ButterKnife.bind(this);
        //百度地图定位
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );    //注册监听函数
        initLocation();
        mLocationClient.start();

        phlv_city.setOnItemClickListener(this);
        //data
        getCities();
        //adapter
        mCityAdatpter = new CityAdapter(this,listData);
        //bind
        phlv_city.setAdapter(mCityAdatpter);
        phlv_city.setOnScrollListener(mCityAdatpter);
        phlv_city.setPinnedHeaderView(getLayoutInflater().inflate(R.layout.view_city_pinnedheader,phlv_city,false));


        bv_city.setOnItemClickListener(new BladeView.OnItemClickListener() {
            @Override
            public void onItemClick(String s) {
                for (int i = 0; i <listData.size() ; i++) {
                    if (listData.get(i).getSymbol().equals(s)) {
                        phlv_city.setSelection(i);
                        break;
                    }
                }
            }
        });




    }




    /**
     * 获取城市列表
     */
    private void getCities() {

        //创建中国城市的数据库
        sqliePath = DBHelp.createSQLiteOfChinaCity();
        SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(sqliePath, null, SQLiteDatabase.OPEN_READONLY);
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT * from T_City", null);
        listData.clear();
        if (cursor.moveToFirst()) {
            do {
                String proID = cursor.getString(cursor.getColumnIndex("ProID"));
                String cityName = cursor.getString(cursor.getColumnIndex("CityName"));
                // 实例化汉字转拼音类
                characterParser = CharacterParser.getInstance();
                pinyinComparator = new PinyinComparator();
                String pinyin = characterParser.getSelling(cityName);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                /**
                 * 重庆市=zhongqingshi
                 亳州市=zuozhoushi
                 濮阳市=zuoyangshi
                 漯河市=zuoheshi
                 儋州市=zuozhoushi
                 */
                if("重庆市".equals(cityName)) {
                    sortString = "C";
                }else if ("亳州市".equals(cityName)) {
                    sortString = "B";
                }else if ("濮阳市".equals(cityName)) {
                    sortString = "P";
                }else if ("漯河市".equals(cityName)) {
                    sortString = "L";
                }else if ("儋州市".equals(cityName)) {
                    sortString = "D";
                }

                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    listData.add(new City(cityName,proID,sortString));
                } else {
                    listData.add(new City(cityName,proID,"#"));
                }
            }while (cursor.moveToNext());
            cursor.close();
        }
        // 根据a-z进行排序源数据
        Collections.sort(listData, pinyinComparator);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        getBankInfo(listData.get(position).getName());
    }


    @OnClick(R.id.tv_city_localname)
    public void clickEvent(View view) {

        //点击自动定位的城市
        if ("定位失败".equals(tv_city_localname.getText().toString())) {
            ToastUtils.showToast("请选择支行所在城市");
        } else {
            getBankInfo(tv_city_localname.getText().toString());
        }

    }


    /**
     * 获取银行卡支行列表信息
     */
    public void getBankInfo(final String mCity) {


        progressDialogUtils.showProgress();

        //构造传输参数
        String bankType = getIntent().getStringExtra("bankType");
        String city = mCity;
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        String sign = Md5Utils.md5Hex(bankType + city + SharedPreferencesUtils.getString(ConstantsUser.userKey));
        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("bankType",bankType);
        map.put("city",city);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.bankInfoCnaps, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {
                        //cnapsList
                        JSONArray jsonArray = jsonObject.getJSONArray("cnapsList");
                        if (jsonArray == null || jsonArray.length() < 1) {
                                    ToastUtils.showToast("该地区没有所属支行");
                        } else {
                            ArrayList<String> bankNames = new ArrayList<String>();
                            ArrayList<String> bankCodes = new ArrayList<String>();
                            for (int i = 0; i <jsonArray.length() ; i++) {
                                bankNames.add(((JSONObject)jsonArray.get(i)).optString("bankName"));
                                bankCodes.add(((JSONObject)jsonArray.get(i)).optString("bankCode"));
                            }
                            Intent intent = new Intent(mContext,SettleBanknameActivity.class);
                            intent.putStringArrayListExtra("bankNames",bankNames);
                            intent.putStringArrayListExtra("bankCodes",bankCodes);
                            intent.putExtra("bankIndex",getIntent().getIntExtra("bankIndex",0));
                            intent.putExtra("httpActionType",getIntent().getStringExtra("httpActionType"));
                            intent.putExtra("banknum",getIntent().getStringExtra("banknum"));
                            startActivity(intent);
                            finish();
                        }
                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });



    }


    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            mLocationClient.stop();
            if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation || location.getLocType() == BDLocation.TypeOffLineLocation) {// GPS定位结果
                tv_city_localname.setText(location.getCity());
            } else {
                tv_city_localname.setText("定位失败");
            }
        }

    }



    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
}
